package mallindex

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/backend/common/utils/miniapp"
	"mall/service/backend/rpc/backendclient"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetSearchKeywordListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 搜索词列表
func NewGetSearchKeywordListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSearchKeywordListLogic {
	return &GetSearchKeywordListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetSearchKeywordListLogic) GetSearchKeywordList(
	req *types.GetSearchKeywordListReq,
	headers *[]*types.Header,
) (resp *types.GetSearchKeywordListResp, err error) {
	userId := jwt.GetUserId(l.ctx)

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	preload := "searchKeyword:Id,Title,LinkType,LinkUrl,ObjectType,ObjectId"
	var filters []string
	filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	if req.Type != nil {
		filters = append(filters, "Type,equalTo:"+strconv.FormatInt(int64(*req.Type), 10))
	} else {
		filters = append(filters, "Type,equalTo:"+strconv.FormatInt(int64(globalkey.SettingSearchKeywordTypeRecommend), 10))
	}

	res, err := l.svcCtx.BackendRpc.GetSearchKeywordList(l.ctx, &backendclient.BaseListReq{
		Offset:     uint32((page - 1) * pageSize),
		Limit:      uint32(pageSize),
		Preload:    pointy.GetPointer(preload),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	var hasNextPage bool
	var hasPreviousPage bool
	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}

	resp = &types.GetSearchKeywordListResp{
		BaseListInfo: types.BaseListInfo{
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}

	if len(res.List) > 0 {
		for _, v := range res.List {
			var linkUrl *string
			if v.LinkType != nil && *v.LinkType == uint32(globalkey.SettingBannerLinkTypeAbsolute) { // H5 绝对路径
				linkUrl = v.LinkUrl
			} else {
				linkUrl = pointy.GetPointer(miniapp.GetLinkUrl(v.LinkType, v.ObjectType, v.ObjectId, v.LinkUrl))
			}
			resp.List = append(resp.List, &types.SearchKeywordInfo{
				Id:         v.Id,
				Type:       v.Type,
				Title:      v.Title,
				Sort:       v.Sort,
				LinkType:   v.LinkType,
				LinkUrl:    linkUrl,
				ObjectId:   v.ObjectId,
				ObjectType: v.ObjectType,
			})
		}
	}

	return resp, nil
}
